[Not Related to Video]
Title
Question
<span style="color:#935690;">#include</span><stdio.h>
<span style="color:#935690;">#define</span> PRODUCT(n) n*n
<span style="color:#935690;">void</span> main()
{
<span style="color:#935690;">int</span> a;
a=<span style="color:#339966;">64</span>/PRODUCT(<span style="color:#339966;">4</span>);
<span style="color:#577299;">printf</span>(<span style="color:#E91E64;">"%d"</span>,a);
}
On compiling above program my gcc compiler gives OUTPUT: 64
Which is wrong output it should be 4 according to definition.
Why it is not considering PRODUCT (4) ?
(QUESTION: B.TECH FIRST YEAR RCS-101 AKTU 2017-18)
C-and-Cpp Understanding-Pointers 05-06 min 50-60 sec
Answers:
Hi,
When you define mathematical expressions you need to provide brackets that follow BODMAS rule; that is the best practice.Here what is happening is that the operation a = 64 / PRODUCT(4); is getting translated to 64 / 4*4, which in interpreted as (64/4)*4 == 64.
Try rewriting the definition as #define PRODUCT(n) (((n)*(n))). Yes, as you might have noticed there is an extra bracket in there, which is again a best practice I have seen followed by others.
Try rewriting the definition as #define PRODUCT(n) (((n)*(n))). Yes, as you might have noticed there is an extra bracket in there, which is again a best practice I have seen followed by others.
Cheers!
When you define mathematical expressions you need to provide brackets that follow BODMAS rule; that is the best practice.Here what is happening is that the operation a = 64 / PRODUCT(4); is getting translated to 64 / 4*4, which in interpreted as (64/4)*4 == 64.
Try rewriting the definition as #define PRODUCT(n) (((n)*(n))). Yes, as you might have noticed there is an extra bracket in there, which is again a best practice I have seen followed by others.
Try rewriting the definition as #define PRODUCT(n) (((n)*(n))). Yes, as you might have noticed there is an extra bracket in there, which is again a best practice I have seen followed by others.
When you define mathematical expressions you need to provide brackets that follow BODMAS rule; that is the best practice.Here what is happening is that the operation a = 64 / PRODUCT(4); is getting translated to 64 / 4*4, which in interpreted as (64/4)*4 == 64.
Try rewriting the definition as #define PRODUCT(n) (((n)*(n))). Yes, as you might have noticed there is an extra bracket in there, which is again a best practice I have seen followed by others.
Try rewriting the definition as #define PRODUCT(n) (((n)*(n))). Yes, as you might have noticed there is an extra bracket in there, which is again a best practice I have seen followed by others.
- <a href="https://en.cppreference.com/w/c/language/operator_precedence">https://en.cppreference.com/w/c/language/operator_precedence</a>
Login to add comment